#include <QPushButton>
#include <QTimer>

#include "digitalsignature.h"
#include "ui_digitalsignature.h"
#include "usersession.h"
#include <QMessageBox>
#include <QDateTime>

DigitalSignature::DigitalSignature(const QString &userId, const QString &signingPurpose, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DigitalSignatureWidget)
    , m_userId(userId)
    , m_signingPurpose(signingPurpose)
    , m_signatureValid(false)
{
    ui->setupUi(this);
    setWindowTitle(tr("Electronic Signature Verification"));
    
    // 设置签名目的说明
    ui->purposeLabel->setText(tr("Signing Purpose: %1").arg(signingPurpose));
    ui->userIdLabel->setText(tr("User ID: %1").arg(userId));
    
    // 连接按钮信号
    connect(ui->verifyButton, &QPushButton::clicked, this, &DigitalSignature::onVerifyClicked);
    connect(ui->cancelButton, &QPushButton::clicked, this, &DigitalSignature::reject);
}

DigitalSignature::~DigitalSignature()
{
    delete ui;
}

bool DigitalSignature::isSignatureValid() const
{
    return m_signatureValid;
}

void DigitalSignature::onVerifyClicked()
{
    if (!validateInput()) {
        return;
    }

    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();

    // 在实际项目中，这里应该使用更安全的身份验证方式
    // 这里简化处理，仅验证用户名是否匹配当前用户
    if (username != m_userId) {
        QMessageBox::warning(this, tr("Verification Failed"), 
                           tr("Username does not match the current user."));
        ui->passwordEdit->clear();
        return;
    }

    // 在实际项目中，这里应该验证密码
    // 这里简化处理，假设密码正确
    m_signatureValid = true;
    
    // 记录签名成功
    QMessageBox::information(this, tr("Success"), 
                            tr("Electronic signature verified successfully."));
    
    // 确保对话框资源正确释放
    QTimer::singleShot(100, this, [this]() {
        accept();
    });
}

bool DigitalSignature::validateInput()
{
    if (ui->usernameEdit->text().isEmpty()) {
        QMessageBox::warning(this, tr("Input Error"), tr("Username cannot be empty"));
        ui->usernameEdit->setFocus();
        return false;
    }
    
    if (ui->passwordEdit->text().isEmpty()) {
        QMessageBox::warning(this, tr("Input Error"), tr("Password cannot be empty"));
        ui->passwordEdit->setFocus();
        return false;
    }
    
    if (ui->reasonEdit->toPlainText().isEmpty()) {
        QMessageBox::warning(this, tr("Input Error"), 
                            tr("You must provide a reason for this electronic signature."));
        ui->reasonEdit->setFocus();
        return false;
    }
    
    return true;
}